<script setup>
import { ref, onMounted, computed } from 'vue'

const users = ref([])
const loading = ref(false)
const errorMessage = ref('')

// 添加搜索和筛选状态
const searchQuery = ref('')
const roleFilter = ref('all')
const statusFilter = ref('all')

// 筛选选项
const roleOptions = [
  { value: 'all', label: '所有角色' },
  { value: 'user', label: '普通用户' },
  { value: 'leader', label: '团长' }
]

const statusOptions = [
  { value: 'all', label: '所有状态' },
  { value: '0', label: '正常' },
  { value: '1', label: '禁用' }
]

// 计算过滤后的用户列表
const filteredUsers = computed(() => {
  return users.value.filter(user => {
    // 搜索条件：用户名包含搜索关键词
    const matchesSearch = user.username.toLowerCase().includes(searchQuery.value.toLowerCase())
    
    // 角色筛选
    const matchesRole = roleFilter.value === 'all' || user.role === roleFilter.value
    
    // 状态筛选
    const matchesStatus = statusFilter.value === 'all' || user.condition === statusFilter.value
    
    return matchesSearch && matchesRole && matchesStatus
  })
})

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  roleFilter.value = 'all'
  statusFilter.value = 'all'
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    errorMessage.value = ''
    
    const token = localStorage.getItem('token')
    if (!token) {
      errorMessage.value = '未登录或登录已过期'
      return
    }

    const response = await fetch('http://localhost:3001/api/admin/users', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    
    const data = await response.json()
    // console.log('服务器响应:', data)
    
    if (data.code === 200) {
      users.value = Array.isArray(data.data) ? data.data : []
      // console.log('用户数据:', users.value)
    } else {
      throw new Error(data.message || '获取用户列表失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
      errorMessage.value = '无法连接到服务器，请检查网络连接'
    } else {
      errorMessage.value = error.message || '网络错误，请稍后重试'
    }
  } finally {
    loading.value = false
  }
}

// 切换用户状态
const toggleUserStatus = async (userId, currentStatus) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      errorMessage.value = '未登录或登录已过期'
      return
    }

    const response = await fetch(`http://localhost:3001/api/admin/users/${userId}/status`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        status: !currentStatus
      })
    })

    const data = await response.json()
    
    if (data.code === 200) {
      const user = users.value.find(u => u.id === userId)
      if (user) {
        user.status = !currentStatus
      }
    } else {
      throw new Error(data.message || '操作失败')
    }
  } catch (error) {
    console.error('切换用户状态失败:', error)
    if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
      errorMessage.value = '无法连接到服务器，请检查网络连接'
    } else {
      errorMessage.value = error.message || '网络错误，请稍后重试'
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchUsers()
})

// 添加编辑相关的状态
const showEditDialog = ref(false)
const editForm = ref({
  user_id: null,
  username: '',
  nickname: '',
  role: '',
  condition: ''
})

// 打开编辑对话框
const openEditDialog = (user) => {
  editForm.value = {
    user_id: user.user_id,
    username: user.username,
    nickname: user.nickname || '',
    role: user.role || 'user',
    condition: user.condition
  }
  showEditDialog.value = true
}

// 保存编辑
const handleSaveEdit = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      errorMessage.value = '未登录或登录已过期'
      return
    }

    const response = await fetch(`http://localhost:3001/api/admin/users/${editForm.value.user_id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        
        role: editForm.value.role,
        condition: editForm.value.condition
      })
    })

    const data = await response.json()
    if (data.code === 200) {
      // 更新本地数据
      const index = users.value.findIndex(u => u.user_id === editForm.value.user_id)
      if (index !== -1) {
        users.value[index] = {
          ...users.value[index],
          ...editForm.value
        }
      }
      showEditDialog.value = false
      alert('更新成功')
    } else {
      throw new Error(data.message || '更新失败')
    }
  } catch (error) {
    
    alert(error.message || '更新失败')
  }
}

// 关闭编辑对话框
const closeEditDialog = () => {
  showEditDialog.value = false
  editForm.value = {
    user_id: null,
    username: '',
    nickname: '',
    role: '',
    condition: ''
  }
}

// 修改删除用户方法
const handleDelete = async (userId) => {
  // 添加确认提示
  if (!confirm('确定要删除这个用户吗？')) {
    return
  }

  try {
    const token = localStorage.getItem('token')
    if (!token) {
      errorMessage.value = '未登录或登录已过期'
      return
    }
    console.log(userId)

    const response = await fetch(`http://localhost:3001/api/admin/users/${userId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    const data = await response.json()
    
    if (data.code === 200) {
      // 从本地数据中移除被删除的用户
      users.value = users.value.filter(user => user.user_id !== userId)
      alert('删除成功')
      // 可选：重新获取用户列表
      await fetchUsers()
    } else {
      throw new Error(data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    alert(error.message || '删除失败')
  }
}
</script>

<template>
  <div class="users-page">
    <div class="page-header">
      <h2>用户管理</h2>
      <button class="refresh-btn" @click="fetchUsers" :disabled="loading">
        <i class="fa-solid fa-rotate" :class="{ 'fa-spin': loading }"></i>
        {{ loading ? '加载中...' : '刷新' }}
      </button>
    </div>

    <!-- 添加搜索和筛选区域 -->
    <div class="filter-section">
      <div class="search-box">
        <i class="fa-solid fa-search"></i>
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索用户名..."
        />
      </div>
      
      <div class="filter-group">
        <select v-model="roleFilter">
          <option 
            v-for="option in roleOptions" 
            :key="option.value" 
            :value="option.value"
          >
            {{ option.label }}
          </option>
        </select>

        <select v-model="statusFilter">
          <option 
            v-for="option in statusOptions" 
            :key="option.value" 
            :value="option.value"
          >
            {{ option.label }}
          </option>
        </select>

        <button class="reset-btn" @click="resetFilters">
          <i class="fa-solid fa-rotate-left"></i>
          重置
        </button>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="errorMessage" class="error-message">
      <i class="fa-solid fa-circle-exclamation"></i>
      {{ errorMessage }}
    </div>

    <!-- 用户列表 -->
    <div class="users-table">
      <table>
        <thead>
          <tr>
            <th>排序</th>
            <th>用户名</th>
            <th>余额</th>
            <th>角色</th>
            <th>注册时间</th>
            <th>状态</th>
            <th>编辑</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading" class="loading-row">
            <td colspan="7" class="loading-cell">
              <i class="fa-solid fa-spinner fa-spin"></i>
              加载中...
            </td>
          </tr>
          <tr v-else-if="filteredUsers.length === 0" class="empty-row">
            <td colspan="7" class="empty-cell">
              {{ searchQuery || roleFilter !== 'all' || statusFilter !== 'all' 
                ? '没有找到匹配的用户' 
                : '暂无用户数据' 
              }}
            </td>
          </tr>
          <tr v-else v-for="user in filteredUsers" :key="user.id">
            <td>{{ user.user_id }}</td>
            <td>{{ user.username }}</td>
            <td>{{ user.balance }}</td>
            <td>{{ user.role=="leader"?"团长":"用户" }}</td>
            <td>{{ user.created_at }}</td>
            <td>
              <span class="status-tag" :class="user.condition == '0'  ? 'active' : 'inactive'">
                {{ user.condition =="0" ? '正常' : '禁用' }}
              </span>
            </td>
            <td>
              <button class="action-btn edit" @click="openEditDialog(user)">
                <i class="fa-solid fa-edit"></i>
                编辑
              </button>
              <button 
                class="action-btn delete"
                @click="handleDelete(user.user_id)"
              >
                <i class="fa-solid fa-trash"></i>
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加编辑对话框 -->
    <div v-if="showEditDialog" class="dialog-overlay" @click="closeEditDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>编辑用户</h3>
          <button class="close-btn" @click="closeEditDialog">
            <i class="fa-solid fa-times"></i>
          </button>
        </div>

        <div class="dialog-body">
          <div class="form-group">
            <label>用户名</label>
            <input type="text" v-model="editForm.username" disabled />
          </div>

          <div class="form-group">
            <label>昵称</label>
            <input type="text" v-model="editForm.nickname" placeholder="请输入昵称" />
          </div>

          <div class="form-group">
            <label>角色</label>
            <select v-model="editForm.role">
              <option value="user">普通用户</option>
              <option value="leader">团长</option>
            </select>
          </div>

          <div class="form-group">
            <label>状态</label>
            <select v-model="editForm.condition">
              <option value="0">正常</option>
              <option value="1">禁用</option>
            </select>
          </div>
        </div>

        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeEditDialog">取消</button>
          <button class="submit-btn" @click="handleSaveEdit">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.users-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: var(--text-color);
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.3s;
}

.refresh-btn:hover:not(:disabled) {
  color: var(--primary-color);
  border-color: var(--primary-color);
}

.refresh-btn:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.error-message {
  padding: 12px;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  border-radius: var(--border-radius);
  color: #ff4d4f;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.users-table {
  background: var(--bg-color);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 16px;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

th {
  background: var(--bg-color-secondary);
  font-weight: 500;
  color: var(--text-color);
}

.loading-cell,
.empty-cell {
  text-align: center;
  color: var(--text-color-secondary);
  padding: 32px !important;
}

.loading-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 2px;
  font-size: 12px;
}

.status-tag.active {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-tag.inactive {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.action-btn {
  padding: 4px 8px;
  border: none;
  border-radius: var(--border-radius);
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 8px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  outline: none;
}

.action-btn:focus {
  outline: none;
}

.action-btn.edit {
  background: #e6f7ff;
  color: var(--primary-color);
}

.action-btn.edit:hover {
  background: #bae7ff;
}

.action-btn.delete {
  background: #fff2f0;
  color: #ff4d4f;
}

.action-btn.delete:hover {
  background: #ffd4d4;
}

/* 添加搜索和筛选相关样式 */
.filter-section {
  margin-bottom: 24px;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 200px;
  position: relative;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--text-color-secondary);
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
}

.filter-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-group select {
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
  cursor: pointer;
}

.reset-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 8px 16px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: var(--bg-color);
  color: var(--text-color);
  cursor: pointer;
  transition: all 0.3s;
}

.reset-btn:hover {
  color: var(--primary-color);
  border-color: var(--primary-color);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-group {
    flex-wrap: wrap;
  }
  
  .filter-group select,
  .reset-btn {
    flex: 1;
    min-width: 120px;
  }
}

/* 添加对话框相关样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  padding: 24px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:disabled {
  background: #f5f5f5;
  cursor: not-allowed;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn {
  background: white;
  border: 1px solid #ddd;
}

.submit-btn {
  background: #1890ff;
  color: white;
  border: none;
}

.submit-btn:hover {
  background: #40a9ff;
}
</style> 